package org.ultrapower.checkuser.core.helper;

import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.util.Bytes;
import org.ultrapower.checkuser.Constants;
import org.ultrapower.checkuser.core.excel.XxlsAbstract;
import org.ultrapower.checkuser.core.hbase.HBaseHelper;
import org.ultrapower.checkuser.core.hbase.HbaseInfo;
import org.ultrapower.checkuser.core.util.FileUtil;
import org.ultrapower.checkuser.core.util.MD5RowKeyGenerator;
import org.ultrapower.checkuser.core.util.MathUtil;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class XxlsFindByHbaseHelper extends XxlsAbstract
{
    //private static final String TABLE_NAME = "USER_INFO";
    private String exportName;

    //excel记录行操作方法
    @Override
    public void optRows(int sheetIndex, int curRow, List rowlist) throws Exception
    {
        String[] s = new String[3];
        for (int i = 0; i < rowlist.size(); i++)
        {
            s[i] = rowlist.get(i) == null ? "" : rowlist.get(i).toString();
        }
        values.add(s);
        if (values.size() % 1000 == 0)
        {
            xx(values);
            values.clear();
        }
    }

    //处理查询结果，通过hbase查询，并把结果保存
    public void xx(List<String[]> list) throws Exception
    {
        List<String> rowKeys = new ArrayList<String>();
        Map<String, String> map = new HashMap<String, String>();
        for (String[] ss : list)
        {
            String phoneNo = ss[0];
            String userName = ss[1];
            String identityCard = ss[2];
            String md5 = new MD5RowKeyGenerator().generatePrefix(phoneNo).toString();
            String rowKey = md5 + "|" + phoneNo + "|" + identityCard;
            rowKeys.add(rowKey);
            map.put(rowKey, userName);
        }
        //批量查询hbase
        Result[] res = new HBaseHelper(HbaseInfo.hbaseConfig).getRecodes(HbaseInfo.TABLE, rowKeys);
        //保存结果数据
        List<String[]> results = new ArrayList<String[]>();
        for (int i=0;i<res.length;i++)
        {
            byte[] b = res[i].getValue(Bytes.toBytes(HbaseInfo.FAMILY), Bytes.toBytes(HbaseInfo.QUALIFIER));
            String rk = Bytes.toString(res[i].getRow());
            String[] value = new String[4];
            value[0] = rowKeys.get(i).split("\\|")[1];
            value[1] = rowKeys.get(i).split("\\|")[2];
            value[2] =list.get(i)[1] ;//   map.get(rowKeys.get(i));
            if (b != null && Bytes.toString(b).equals(map.get(rk)))
            {
                value[3] = "0";
            } else
            {
                value[3] = "999";
            }
            results.add(value);
        }
        FileUtil.exportCsv(new File(Constants.OUTPATH, exportName + ".csv"), results, true);

    }

    //处理Excel中sheet1中的信息
    public String  handleUserByIdAndPhone(File file) throws Exception
    {
        this.exportName= MathUtil.redom();
        processOneSheet(file.getPath(), 1);
        if (values.size() > 0) xx(values);
        return exportName + ".csv";
    }
    //导出
    public void fileDownLoad(HttpServletRequest request, HttpServletResponse response,File file,String fileName) throws Exception
    {
        FileInputStream fos = null;
        ServletOutputStream sos = null;
        try
        {
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("gbk"), "iso8859-1"));
            response.setContentType("application/octet-stream");
            response.setContentType("application/OCTET-STREAM;charset=UTF-8");
            response.addHeader("Content-Length", "" + file.length());
            byte b[] = new byte[1024];//1M
            int read = 0;
            fos = new FileInputStream(file);
            sos = response.getOutputStream();
            while ((read = fos.read(b)) != -1)
            {
                sos.write(b, 0, read);//每次写1M
            }
        } catch (Exception e)
        {
            e.printStackTrace();
            throw new Exception("文件导出失败");
        } finally
        {
                if (sos != null)sos.close();
                if (fos != null)fos.close();
        }
    }
    public static void main(String[] args) throws Exception
    {
        XxlsFindByHbaseHelper howto = new XxlsFindByHbaseHelper();
        // howto.processOneSheet("F:/1/1234.xlsx", 1);
        //      howto.processAllSheets("F:/new.xlsx");
    }


}
